#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import datetime
import time
ETC_DIR = '/etc/djwatchd/'
STATS_DIR = '/tmp/djwatch/'

import sys; sys.path.insert(0, ETC_DIR)
import BaseHTTPServer

import settings
from utils import unpack, jsonify

class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        return BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

    def get_stat(self):
        start = time.time()
        file_format = settings.STAT_GRAB_FILE_FORMAT
        response_format = settings.STAT_RESPONSE_DATETIME_FORMAT
        try:
            stats = os.listdir(STATS_DIR)
            stats.sort()
            result = dict([
                    datetime.datetime.strptime(fn, file_format).\
                        strftime(response_format),
                    unpack( open(os.path.join(STATS_DIR, fn)).read() )
                ] for fn in stats)
        except:
            import traceback
            result = {'_error': traceback.format_exc()}
        result['_time'] = time.time() - start
        return result

    def do_GET(self):
        self.send_response(200)
        #self.send_header('Content-type', 'text/json')
        self.send_header('Content-type', 'text/html')  # for easy debug in browser
        self.end_headers()
        self.wfile.write(jsonify(self.get_stat()))

def main():
    addr = (settings.BIND_ADDRESS, settings.BIND_PORT)
    httpd = BaseHTTPServer.HTTPServer(addr, Handler)
    sys.stdout.write('Djwatch agent started at http://%s:%s\n' % addr)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        sys.stderr.write('Djwatch agent stopped\n')
        return

if __name__ == '__main__':
    main()
